package com.api.tournament.queue;

import com.api.common.EmailUtil;
import com.api.tournament.model.Tournament;
import com.api.tournament.service.TournamentService;
import com.api.tournament.vo.TournamentTeamUserVo;
import com.api.user.model.UserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.concurrent.DelayQueue;

@Component
public class TournamentStartDelayedService {
    Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    private TournamentService tournamentService;

    private DelayQueue<TournamentStartDelayedMessage> delayQueue = new DelayQueue<>();

    public DelayQueue<TournamentStartDelayedMessage> getDelayQueue() {
        return delayQueue;
    }


    public void offer(TournamentStartDelayedMessage delayMessage){
        delayQueue.offer(delayMessage);
        logger.info("队列添加消息 执行时间: {}, 队列长度 {}" , new Date(delayMessage.getStartDate()), delayQueue.size());

    }

    public void remove(TournamentStartDelayedMessage delayMessage){
        boolean isRemove = delayQueue.remove(delayMessage);
        logger.info("队列删除消息: {}, 队列长度 {}" ,isRemove, delayQueue.size());
    }

    public void sendCheckInEmail(TournamentStartDelayedMessage delayMessage){
        List<TournamentTeamUserVo> userVos = tournamentService.joinUser(delayMessage.getTournamentId());
        for (TournamentTeamUserVo userVo : userVos) {
            if(userVo.getCheckIn()!=null && !userVo.getCheckIn()){
                EmailUtil.gmailSender(userVo.getEmail(),"比赛将于30分钟后开始，请前往签到页面签到",null);
            }
        }
        logger.info("发送签到提醒");
    }

    @PostConstruct
    private void init() {
        logger.info("赛事提醒队列初始化 未开始的赛事加入队列中");
        //每次启动 未开始的赛事加入队列
        List<Tournament> tournaments = tournamentService.listByStatus(2);
        for (Tournament tournament : tournaments) {
            if(tournament.getTournamentTime()!=null && tournament.getTournamentTime() > System.currentTimeMillis()){
                TournamentStartDelayedMessage message = new TournamentStartDelayedMessage();
                //提前30分钟
                message.setStartDate(tournament.getTournamentTime()-1800000);
                message.setTournamentId(tournament.getId());
                message.setTournamentName(tournament.getTournamentName());
                this.offer(message);
            }
        }
        new Thread(new TournamentStartConsumer(this)).start();
    }
}
